这篇内容是在有道云旧笔记基础上重新整理的 Vue/Vite 工程实践 笔记。原始记录偏碎片化,这里补充了使用场景、阅读顺序和落地时需要注意的边界,方便以后在项目里快速复用。
适用场景 Vue/Vite 项目中遇到配置、组件封装、构建或运行时问题时,作为排查入口。 需要把一次性调试经验沉淀成团队内可复用的前端工程实践。 迁移旧项目或升级依赖时,用来对照检查环境变量、插件和组件行为差异。 核心要点 正文以代码或命令片段为主,阅读时建议先确认目标问题,再挑选对应片段验证。 保留了 1 段可直接参考的代码或命令,主要涉及 javascript,复制前需要按当前项目路径、版本和变量名做调整。 在项目中我们可能会遇到一个问题,就是很多地方使用到了第三方的外链,比如图片、CSS、JS,由于项目是团队开发,有时候还不知道项目哪些地方引用了第三方的外链,所以我们不可能通过 link 标签的形式将这些第三方外链一个个引入并开启 DNS 预解析。
这个时候需要写一个插件去帮我们查找项目中所有的引入的第三方外链,在网上搜了下找不到满足需求的插件,只能自己写了,由于 Vite 项目使用 rollup 打包的,而 Vue-cli 项目用的是 webpack,不同的工具打包机制是不一样的,所以不采用插件的形式,在运行打包命令的时候运行一段代码,去修改打包的结果,这里以 Vite 工程为例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 "scripts" : { "build" : "vite bulid && node ./scripts/dns-prefetch.js" } const fs = require ('fs' )const path = require ('path' )const { parse } = require ('node-html-parser' )const { glob } = require ('glob' )const urlRegex = require ('url-regex' )const urlPattern = /(https?:const urls = new Set ()async function searchDomin () { const files = await glob ('dist/**/*.{html,css,js}' ) for (const file of files) { const source = fs.readFileSync (file, 'utf-8' ) const matches = source.match (urlRegex ({ strict: true })) if (matches) { matches.forEach ((url) => { const match = url.match (urlPattern) if (match && match[1 ]) { urls.add (match[1 ]) } }) } } } async function insertLinks () { const files = await glob ('dist/**/*.html' ) const links = [...urls].map ((url) => `<link rel="dns-prefetch" href="${url}" />` ).join ('\n' ) for (const file of files) { const html = fs.readFileSync (file, 'utf-8' ) const root = parse (html) const head = root.querySelector ('head' ) head.insertAdjacentHTML ('afterbegin' , links) fs.writeFileSync (file, root.toString ()) } } async function main () { await searchDomin () await insertLinks () } main ()
实践检查清单 先确认 Vue、Vite、Node、包管理器版本,再判断示例是否需要按当前工程结构调整。 涉及构建或插件配置时,建议同时验证开发环境和生产构建结果。 涉及 UI 或浏览器行为时,至少在桌面端和移动端各验证一次关键路径。 涉及接口、服务端或权限逻辑时,补充失败分支和权限边界测试。 复盘小结 这篇笔记更适合作为问题排查或方案落地前的速查材料。后续如果在真实项目中再次遇到同类问题,可以继续把具体版本、报错信息、最终取舍和验证结果补到对应小节里,让它从代码片段逐步沉淀成完整方案。
Author: 蓝思同学
Permalink: https://www.lancema.com/posts/2024/vue/网页加载优化 - DNS预解析.html
Slogan: small is beautiful, small is powerful !